<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>已售出票据 - 电影院管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            line-height: 1.6;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .nav {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }
        
        .logo {
            font-size: 24px;
            font-weight: bold;
        }
        
        .nav-links {
            display: flex;
            gap: 30px;
        }
        
        .nav-links a {
            color: white;
            text-decoration: none;
            font-weight: 500;
            transition: opacity 0.3s;
        }
        
        .nav-links a:hover {
            opacity: 0.8;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .welcome-section {
            background: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
            transition: transform 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .stat-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #666;
            font-size: 16px;
        }
        
        .tickets-section {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .section-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .filter-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .filter-options {
            display: flex;
            gap: 10px;
        }
        
        .filter-btn {
            padding: 8px 15px;
            background-color: #f0f0f0;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .filter-btn.active {
            background-color: #667eea;
            color: white;
        }
        
        .filter-btn:hover {
            background-color: #e0e0e0;
        }
        
        .filter-btn.active:hover {
            background-color: #5a6fd6;
        }
        
        .search-box {
            display: flex;
            gap: 10px;
        }
        
        .search-input {
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            width: 250px;
        }
        
        .btn {
            padding: 10px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            font-weight: 500;
            transition: transform 0.2s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .tickets-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        .tickets-table th,
        .tickets-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .tickets-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #333;
        }
        
        .tickets-table tr:hover {
            background-color: #f5f5f5;
        }
        
        .ticket-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-active {
            background-color: #d1e7dd;
            color: #0f5132;
        }
        
        .status-refunded {
            background-color: #f8d7da;
            color: #842029;
        }
        
        .action-btn {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            background-color: #e9ecef;
            color: #495057;
            border: none;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .action-btn:hover {
            background-color: #dee2e6;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 5px;
        }
        
        .page-item {
            display: inline-block;
            min-width: 32px;
            height: 32px;
            text-align: center;
            line-height: 32px;
            border-radius: 4px;
            background-color: #fff;
            border: 1px solid #ddd;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .page-item.active {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .page-item:hover {
            background-color: #f0f0f0;
        }
        
        .page-item.active:hover {
            background-color: #5a6fd6;
        }
        
        /* 排序相关样式 */
        .sortable {
            cursor: pointer;
            position: relative;
        }
        
        .sort-icon {
            font-size: 12px;
            margin-left: 5px;
            opacity: 0.5;
        }
        
        .sortable.asc .sort-icon {
            content: '↑';
            opacity: 1;
        }
        
        .sortable.desc .sort-icon {
            content: '↓';
            opacity: 1;
        }
        
        /* 高亮搜索结果 */
        .highlight {
            background-color: #fff3cd;
        }
        
        /* 导出按钮样式 */
        #exportBtn {
            margin-left: 10px;
        }
        
        @media (max-width: 768px) {
            .filter-bar {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .search-box {
                width: 100%;
                margin-top: 10px;
            }
            
            .search-input {
                width: 100%;
            }
            
            .tickets-table {
                display: block;
                overflow-x: auto;
            }
        }
    </style>
</head>
<body>
    <header class="header">
        <nav class="nav">
            <div class="logo">🎬 前台控制台</div>
            <div class="nav-links">
                <a href="/receptionist/dashboard">控制台</a>
                <a href="/receptionist/movies">影片信息</a>
                <a href="/receptionist/screenings">场次信息</a>
                <a href="/receptionist/sell-ticket">售票功能</a>
                <a href="/receptionist/refund-ticket">退票功能</a>
                <a href="/receptionist/sold-tickets" class="active">已售票据</a>
            </div>
            <div class="user-info">
                <span th:text="|前台：${session.user != null ? session.user.username : '未登录'}|">前台</span>
                <a href="/auth/logout" class="btn btn-sm">退出登录</a>
            </div>
        </nav>
    </header>

    <div class="container">
        <div class="welcome-section">
            <h1>已售出票据查询</h1>
            <p>您可以在此页面查看所有已售出的电影票信息</p>
        </div>

        <!-- 统计数据 -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">🎫</div>
                <div class="stat-number" th:text="${totalTickets ?: 0}">0</div>
                <div class="stat-label" th:text="|${periodName}票据总数|">票据总数</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">💰</div>
                <div class="stat-number" th:text="|¥${totalSales ?: 0}|">¥0</div>
                <div class="stat-label" th:text="|${periodName}销售总额|">销售总额</div>
            </div>
        </div>

        <!-- 票据列表 -->
        <div class="tickets-section">
            <h2 class="section-title">票据列表</h2>
            
            <div class="filter-bar">
                <div class="filter-options">
                    <a th:href="@{/receptionist/sold-tickets(period='all')}" class="filter-btn" th:classappend="${period == 'all' ? 'active' : ''}">全部</a>
                    <a th:href="@{/receptionist/sold-tickets(period='today')}" class="filter-btn" th:classappend="${period == 'today' ? 'active' : ''}">今日</a>
                    <a th:href="@{/receptionist/sold-tickets(period='week')}" class="filter-btn" th:classappend="${period == 'week' ? 'active' : ''}">本周</a>
                    <a th:href="@{/receptionist/sold-tickets(period='month')}" class="filter-btn" th:classappend="${period == 'month' ? 'active' : ''}">本月</a>
                </div>
                
                <div class="search-box">
                    <input type="text" id="ticketSearch" class="search-input" placeholder="搜索电子票号、订单号、影片名称或座位号">
                    <button class="btn" onclick="searchTickets()">搜索</button>
                    <button class="btn" id="exportBtn" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">导出数据</button>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="tickets-table" id="ticketsTable">
                    <thead>
                        <tr>
                            <th class="sortable" data-sort="ticketNumber">电子票号 <span class="sort-icon">↕</span></th>
                            <th class="sortable" data-sort="orderId">订单号 <span class="sort-icon">↕</span></th>
                            <th class="sortable" data-sort="movieTitle">影片名称 <span class="sort-icon">↕</span></th>
                            <th>放映厅</th>
                            <th class="sortable" data-sort="screeningTime">场次时间 <span class="sort-icon">↕</span></th>
                            <th>座位号</th>
                            <th class="sortable" data-sort="price">票价 <span class="sort-icon">↕</span></th>
                            <th class="sortable" data-sort="createdAt">售出时间 <span class="sort-icon">↕</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr th:each="detail : ${ticketDetails}" th:id="'ticket-' + ${detail.ticket.ticketNumber}">
                            <td th:text="${detail.ticket.ticketNumber}">TK123456</td>
                            <td>
                                <a th:text="${detail.ticket.orderId}">ORD123456</a>
                            </td>
                            <td th:text="${detail.movie != null ? detail.movie.title : '未知影片'}">电影名称</td>
                            <td th:text="${detail.room != null ? detail.room.name : '未知放映厅'}">1号厅</td>
                            <td th:text="${detail.screening != null ? #temporals.format(detail.screening.startTime, 'yyyy-MM-dd HH:mm') : '未知时间'}">2023-06-01 14:30</td>
                            <td th:text="${detail.ticket.seatNumber}">A1</td>
                            <td th:text="|¥${detail.ticket.price}|">¥45.00</td>
                            <td th:text="${#temporals.format(detail.ticket.createdAt, 'yyyy-MM-dd HH:mm')}">2023-06-01 10:30</td>
                            </td>
                        </tr>
                        <tr th:if="${ticketDetails == null || ticketDetails.empty}">
                            <td colspan="9" style="text-align: center;">暂无票据数据</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // 搜索功能
        function searchTickets() {
            const searchValue = document.getElementById('ticketSearch').value.toLowerCase();
            const table = document.getElementById('ticketsTable');
            const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
            let foundResults = false;
            
            // 移除之前的高亮
            const highlights = document.querySelectorAll('.highlight');
            highlights.forEach(el => el.classList.remove('highlight'));
            
            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                if (row.cells.length <= 1) continue; // 跳过"暂无票据数据"行
                
                const ticketNumber = row.cells[0].textContent.toLowerCase();
                const orderId = row.cells[1].textContent.toLowerCase();
                const movieTitle = row.cells[2].textContent.toLowerCase();
                const seatNumber = row.cells[5].textContent.toLowerCase();
                
                if (searchValue === '') {
                    row.style.display = '';
                    continue;
                }
                
                if (ticketNumber.includes(searchValue) || 
                    orderId.includes(searchValue) || 
                    movieTitle.includes(searchValue) || 
                    seatNumber.includes(searchValue)) {
                    row.style.display = '';
                    foundResults = true;
                    
                    // 高亮匹配的内容
                    highlightCell(row.cells[0], ticketNumber, searchValue);
                    highlightCell(row.cells[1], orderId, searchValue);
                    highlightCell(row.cells[2], movieTitle, searchValue);
                    highlightCell(row.cells[5], seatNumber, searchValue);
                } else {
                    row.style.display = 'none';
                }
            }
            
            // 显示搜索结果提示
            if (searchValue !== '' && !foundResults) {
                alert('未找到匹配的结果');
            }
        }
        
        // 高亮单元格中的匹配文本
        function highlightCell(cell, text, searchValue) {
            if (text.includes(searchValue)) {
                cell.classList.add('highlight');
            }
        }
        
        // 排序功能
        let currentSort = { column: null, direction: 'asc' };
        
        function sortTable(column) {
            const table = document.getElementById('ticketsTable');
            const tbody = table.getElementsByTagName('tbody')[0];
            const rows = Array.from(tbody.getElementsByTagName('tr'));
            
            // 跳过"暂无票据数据"行
            const dataRows = rows.filter(row => row.cells.length > 1);
            
            // 更新排序方向
            if (currentSort.column === column) {
                currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
                currentSort.column = column;
                currentSort.direction = 'asc';
            }
            
            // 更新表头样式
            const headers = table.querySelectorAll('th.sortable');
            headers.forEach(header => {
                header.classList.remove('asc', 'desc');
                if (header.dataset.sort === column) {
                    header.classList.add(currentSort.direction);
                }
            });
            
            // 排序行
            dataRows.sort((a, b) => {
                let valueA, valueB;
                
                switch(column) {
                    case 'ticketNumber':
                        valueA = a.cells[0].textContent.trim();
                        valueB = b.cells[0].textContent.trim();
                        break;
                    case 'orderId':
                        valueA = a.cells[1].textContent.trim();
                        valueB = b.cells[1].textContent.trim();
                        break;
                    case 'movieTitle':
                        valueA = a.cells[2].textContent.trim();
                        valueB = b.cells[2].textContent.trim();
                        break;
                    case 'screeningTime':
                        valueA = new Date(a.cells[4].textContent.trim());
                        valueB = new Date(b.cells[4].textContent.trim());
                        break;
                    case 'price':
                        valueA = parseFloat(a.cells[6].textContent.replace('¥', '').trim());
                        valueB = parseFloat(b.cells[6].textContent.replace('¥', '').trim());
                        break;
                    case 'createdAt':
                        valueA = new Date(a.cells[7].textContent.trim());
                        valueB = new Date(b.cells[7].textContent.trim());
                        break;
                    default:
                        valueA = a.cells[0].textContent.trim();
                        valueB = b.cells[0].textContent.trim();
                }
                
                // 比较值
                let comparison = 0;
                if (valueA > valueB) {
                    comparison = 1;
                } else if (valueA < valueB) {
                    comparison = -1;
                }
                
                // 根据排序方向返回结果
                return currentSort.direction === 'asc' ? comparison : -comparison;
            });
            
            // 重新添加行到表格
            dataRows.forEach(row => tbody.appendChild(row));
            
            // 如果有"暂无票据数据"行，保持在最后
            rows.filter(row => row.cells.length <= 1).forEach(row => tbody.appendChild(row));
        }
        
        // 导出功能
        function exportToCSV() {
            const table = document.getElementById('ticketsTable');
            const rows = table.querySelectorAll('tbody tr');
            const headers = Array.from(table.querySelectorAll('thead th')).map(th => th.textContent.trim().replace(/[↕↑↓]/g, '').trim());
            
            let csvContent = headers.join(',') + '\n';
            
            rows.forEach(row => {
                if (row.cells.length <= 1 || row.style.display === 'none') return; // 跳过隐藏行和"暂无票据数据"行
                
                const rowData = Array.from(row.cells).map(cell => {
                    // 移除操作列中的HTML
                    let content = cell.textContent.trim();
                    // 处理CSV中的逗号和引号
                    content = content.replace(/"/g, '""');
                    if (content.includes(',')) {
                        content = '"' + content + '"';
                    }
                    return content;
                });
                
                csvContent += rowData.join(',') + '\n';
            });
            
            // 创建下载链接
            const encodedUri = 'data:text/csv;charset=utf-8,\uFEFF' + encodeURIComponent(csvContent);
            const link = document.createElement('a');
            link.setAttribute('href', encodedUri);
            link.setAttribute('download', `票据数据_${new Date().toISOString().slice(0, 10)}.csv`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 事件监听
        document.addEventListener('DOMContentLoaded', function() {
            // 监听搜索框输入事件
            document.getElementById('ticketSearch').addEventListener('keyup', function(event) {
                if (event.key === 'Enter') {
                    searchTickets();
                }
            });
            
            // 监听排序点击事件
            document.querySelectorAll('th.sortable').forEach(header => {
                header.addEventListener('click', function() {
                    sortTable(this.dataset.sort);
                });
            });
            
            // 监听导出按钮点击事件
            document.getElementById('exportBtn').addEventListener('click', exportToCSV);
        });
    </script>
</body>
</html>